package org.yelongframework.excel;

import org.apache.commons.lang3.StringUtils;
import org.yelongframework.commons.lang.IntegerUtil;
import org.yelongframework.commons.lang.StringUtil;
import org.yelongframework.core.pair.Pair;
import org.yelongframework.util.Assert;
import org.yelongframework.util.EnglishLetters;

/**
 * Excel工具类
 * 
 * @since 1.0.0
 */
public final class ExcelUtils {

	/** 英文字母长度 */
	private static final int ENGLISH_LETTER_COUNT = EnglishLetters.LETTER_COUNT;

	// ==================================================构造器==================================================

	private ExcelUtils() {
	}

	// ==================================================解析坐标==================================================

	/**
	 * 解析单元格坐标为单元格行列索引
	 * 
	 * @param cellCoord 单元格坐标
	 * @return 单元格的行列索引。left为行坐标，right为列坐标。索引从1开始。
	 */
	public static Pair<Integer, Integer> resolveCellCoord(String cellCoord) {
		Assert.notNull(cellCoord, "cellCoord cannot be null");
		Integer rowIndex = IntegerUtil.valueOfByEnd(cellCoord);
		if (null == rowIndex) {
			throw new IllegalArgumentException("【" + cellCoord + "】不是一个有效的坐标");
		}
		String cellCoordColumn = cellCoord.substring(0, cellCoord.lastIndexOf(rowIndex.toString()));
		if (StringUtils.isBlank(cellCoordColumn)) {
			throw new IllegalArgumentException("【" + cellCoord + "】不是一个有效的坐标");
		}
		int columnIndex = resolveCellCoordColumn(cellCoordColumn);
		return new Pair<>(rowIndex, columnIndex);
	}

	/**
	 * 解析单元格列坐标
	 * 
	 * @param cellCoordColumn 单元格列坐标
	 * @return 单元格列索引
	 */
	public static int resolveCellCoordColumn(String cellCoordColumn) {
		Assert.notNull(cellCoordColumn, "cellCoordColumn cannot be null");
		char[] columnIndexStringCharArray = StringUtil.reverse(cellCoordColumn).toCharArray();
		int columnIndex = 0;
		for (int i = 0; i < columnIndexStringCharArray.length; i++) {
			columnIndex += Math.pow(ENGLISH_LETTER_COUNT, i)
					* (EnglishLetters.getUpperCaseIndex(columnIndexStringCharArray[i]) + 1);
		}
		return columnIndex;
	}

	// ==================================================生成坐标==================================================

	/**
	 * 将单元格行列索引转换为单元格坐标
	 * 
	 * @param rowIndex    行索引。从1开始
	 * @param columnIndex 列索引。从1开始
	 * @return 单元格坐标
	 */
	public static String generateCellCoord(int rowIndex, int columnIndex) {
		return generateCellCoordColumn(columnIndex) + rowIndex;
	}

	/**
	 * 将单元格列索引转换为单元格列坐标
	 * 
	 * @param cellColumnIndex 单元格列索引
	 * @return 单元格列坐标
	 */
	public static String generateCellCoordColumn(int cellColumnIndex) {
		StringBuilder cellCoord = new StringBuilder();
		while (cellColumnIndex > ENGLISH_LETTER_COUNT) {
			// 余值为最后一个字符
			cellCoord.append(EnglishLetters.getUpperCase(cellColumnIndex % ENGLISH_LETTER_COUNT));
			cellColumnIndex = cellColumnIndex / ENGLISH_LETTER_COUNT;
		}
		cellCoord.append(EnglishLetters.getUpperCase(cellColumnIndex));
		return StringUtil.reverse(cellCoord.toString());
	}

}
